<?php

class homeActions extends sfActions {
  
  public function executeIndexPreLaunch(sfWebRequest $request) {
    
  }

  public function executeIndex(sfWebRequest $request) {
    if (sfConfig::get('sf_environment') == 'prod') {
      $this->forward('home', 'indexPreLaunch');
    }
    
    if (!$this->getUser()->getAttribute(Constants::SESSION_USER_LATITUDE) || !$this->getUser()->getAttribute(Constants::SESSION_USER_LONGITUDE)) {
      $monviaHttpClient = new MonviaHttpClient();
      $uri = 'http://freegeoip.net/json/' . ServerUtil::getUserIp();
      $monviaHttpClient->get($uri, array());

      if ($monviaHttpClient->isResponseOk()) {
        $data = $monviaHttpClient->getResponseBody(true);
        $data = json_decode($data, true);
        if (isset($data['city']) && isset($data['latitude']) && isset($data['longitude'])) {
          $this->getUser()->setAttribute(Constants::SESSION_USER_CITY, trim($data['city']));
          $this->getUser()->setAttribute(Constants::SESSION_USER_LATITUDE, trim($data['latitude']));
          $this->getUser()->setAttribute(Constants::SESSION_USER_LONGITUDE, trim($data['longitude']));
        }
      }
    }

    $this->noResults = false;
    $this->numResults = null;
    if ($request->isMethod('post')) {
      $formData = $request->getParameter(UserSignupForm::FORM_NAME);
      $offerList = OFFERTable::getInstance()->findActiveOrderByNearest($this->getUser()->getAttribute(Constants::SESSION_USER_LATITUDE), $this->getUser()->getAttribute(Constants::SESSION_USER_LONGITUDE), $formData[MainSearchForm::FIELD_RADIUS], $formData[MainSearchForm::FIELD_LOCATION], $formData[MainSearchForm::FIELD_MOVIE_TITLE], $formData[MainSearchForm::FIELD_PRICE], $formData[MainSearchForm::FIELD_DATE], $formData[MainSearchForm::FIELD_TIME_FROM], $formData[MainSearchForm::FIELD_TIME_TO], $formData[MainSearchForm::FIELD_MERCHANT]);
      if (!count($offerList)) {
        $offerList = OFFERTable::getInstance()->findActiveOrderByNearest($this->getUser()->getAttribute(Constants::SESSION_USER_LATITUDE), $this->getUser()->getAttribute(Constants::SESSION_USER_LONGITUDE));
        $this->noResults = true;
      } else {
        $this->numResults = count($offerList);
      }
    } else {
      $offerList = OFFERTable::getInstance()->findActiveOrderByNearest($this->getUser()->getAttribute(Constants::SESSION_USER_LATITUDE), $this->getUser()->getAttribute(Constants::SESSION_USER_LONGITUDE));
    }

    $this->offerList = $offerList;
    $this->getUser()->getAttributeHolder()->remove('quantity');
  }

  public function executeAbout(sfWebRequest $request) {

  }

  public function executeWhat(sfWebRequest $request) {

  }

  public function executePrivacy(sfWebRequest $request) {

  }

  public function executeTerms(sfWebRequest $request) {

  }

  public function executeContact(sfWebRequest $request) {
    require_once(sfConfig::get('sf_lib_dir') . '/vendor/recaptcha/recaptchalib.php');
    $errorCollector = array();

    $trans = SystemUtil::beginDoctrineTransaction();

    try {
      $this->form = new ContactUsForm();

      if ($request->isMethod('post')) {
        $formData = $request->getParameter(ContactUsForm::FORM_NAME);
        $this->form->bind($formData);

        if ($this->form->isValid()) {
          $email = new EMAIL();
          $email->setEmailTo(sfConfig::get('app_emailgroup_admin'));
          $email->setSubject('Contact Form: ' . ContactUsForm::$subjects[$formData[ContactUsForm::FIELD_SUBJECT]]);
          $data = array(
                  'first_name'      => $formData[ContactUsForm::FIELD_FIRST_NAME],
                  'last_name'       => $formData[ContactUsForm::FIELD_LAST_NAME],
                  'email'           => $formData[ContactUsForm::FIELD_EMAIL],
                  'phone'           => $formData[ContactUsForm::FIELD_PHONE],
                  'subject'         => ContactUsForm::$subjects[$formData[ContactUsForm::FIELD_SUBJECT]],
                  'message'         => $formData[ContactUsForm::FIELD_MESSAGE],
                  'ip_address'      => ServerUtil::getUserIp()
          );
          $email->setMessage($data);
          $email->setTemplateFile('contactUs');
          $email->setContentType(emailTask::CONTENT_TYPE_HTML);
          $email->save();

          if (isset($formData[ContactUsForm::FIELD_COPY_ME])) {
            $email = $email->copy(false);
            $email->setEmailTo($formData[ContactUsForm::FIELD_EMAIL]);
            unset($data['ip_address']);
            $email->setMessage($data);
            $email->save();
          }

          SystemUtil::commitDoctrineTransaction($trans);

          $this->redirect('@contact?success=1');
        }
      }
    } catch (Exception $e) {
      $errorCollector[] = LangUtil::getText('error_save_failed');
      SystemUtil::rollbackDoctrineTransaction($trans);
    }

    $this->errorCollector = $errorCollector;
  }

  public function executeLocker(sfWebRequest $request) {
    if ($request->getParameter('day') == date('d')) {
      $status = ($request->getParameter('status') == '1') ? true : false;

      if ($status === true) {
        if (!file_exists(sfConfig::get('app_lock_filename'))) {
          file_put_contents(sfConfig::get('app_lock_filename'), '');
        }
        echo '<img src="http://www.veryicon.com/icon/png/System/Soft%20Scraps/Lock%20Lock.png" alt="Locked" />';
      } else {
        if (file_exists(sfConfig::get('app_lock_filename'))) {
          unlink(sfConfig::get('app_lock_filename'));
        }
        echo '<img src="http://icons.iconarchive.com/icons/deleket/soft-scraps/256/Lock-Unlock-icon.png" alt="Unlocked" />';
      }
    }

    return sfView::NONE;
  }

  public function executeError404(sfWebRequest $request) {

  }

  public function executeLocationSearch(sfWebRequest $request) {
    $postCodeList = POST_CODETable::getInstance()->findByCityOrCode($request->getParameter('q'));
    $results = array();
    foreach ($postCodeList as $postCode) {
      $results[] = $postCode->getCity() . ' (' . $postCode->getCode() . ')';
    }
    return $this->renderText(implode("\n", $results));
  }

  public function executeMovieSearch(sfWebRequest $request) {
    $movieList = OFFERTable::getInstance()->findActiveMovies($request->getParameter('q'));
    $results = array();
    foreach ($movieList as $movie) {
      $results[] = $movie->getTitle();
    }
    return $this->renderText(implode("\n", $results));
  }
}